<script setup lang="ts">
import {ref} from "vue"
import { compress } from 'squoosh-compress';
import WebSocketUploadFile from "jack-websocket-uploadfile";
import {GlobalInfo} from "../GlobalInfo";
import {DocService} from "../apis/DocService";
import {useRoute,onBeforeRouteUpdate} from "vue-router"
import { AdminService } from "@/apis/AdminService";
import { useToast } from "vue-toastification";

const toast = useToast();
const text = ref("")
const isEditing = GlobalInfo.isEditing;

const route = useRoute();
var docId = route.params.id;

const loadContent = async ()=>{    
    GlobalInfo.CurrentDocId.value = <any>docId;
    text.value = await DocService.GetDocContent(docId,new Date().getTime());
    
}
loadContent();

onBeforeRouteUpdate((to,from)=>{
    docId = to.params.id;
    console.log("路由变更，docid:",docId);
    loadContent();
});

function uploadImage(file:File):Promise<string>{
    return new Promise((resolve,reject)=>{
        var uploader = new WebSocketUploadFile(file,GlobalInfo.ServerUrl);
        uploader.auth = GlobalInfo.Token;
        uploader.state = JSON.stringify({DocId:docId});

            uploader.onError = (s,err)=>{
                reject(err);
            };
            uploader.onCompleted = async (s:WebSocketUploadFile,tranId:string)=>{
                console.log("上传完毕");
                var url = await GlobalInfo.getContent("/Doc/GetImagePath?tranId=" + tranId);
                resolve(url);
            };
            uploader.upload();

    });

};

const save = async ()=>{
    try {
        await AdminService.UpdateDoc(null,text.value,docId);
        toast("保存成功");
    }
    catch(e){
        GlobalInfo.showError(e);
    }
}

const handleUploadImage = async (event : any, insertImage : any, files : File[])=>{  
    try {
        for (var i = 0; i < files.length; i++) {      
            console.log("图片大小：" , files[i].size);      
            const data: File = await compress(
                files[i],
                {
                    type: "browser-jpeg",
                    options: {
                        quality: 0.5
                    }
                },
                "a.jpg"
            );
            console.log(data.arrayBuffer);
            console.log("转换后大小：" , data.size);
            var imgurl = await uploadImage(data);

            insertImage({
                url: `${GlobalInfo.ServerUrl}/docs/${docId}/imgs/${imgurl}`
            });
        }
    }
    catch (e) {
        alert((<any>e).message);
    }
   
}
</script>

<template>
    <div class="root">
        <div class="container">
            <v-md-editor :disabled-menus="[]" @save="save"
    @upload-image="handleUploadImage" v-model="text"></v-md-editor>
        </div>       
    </div>
</template>

<style scoped>
.root{
    height: 100%;
    flex: 1;
    position: relative;
}
.container{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}
</style>